﻿using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Functions;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables
{
    [InjectClass]
    public class CollectionsServer : ICollectionsServer
    {
        private readonly ServerRepository _serverRepository;

        public CollectionsServer(DbContext dbContext)
        {
            _serverRepository = new ServerRepository(dbContext);
        }

        public async Task<ResponseApiDto> CancelCollection(CancelCollectionDto dto,int bid)
        {
            Collection collection = await _serverRepository.collectionsEFCore.Query(d => d.CId == dto.id && d.CBusinessId == bid).SingleOrDefaultAsync();
            if (collection == null)
            {
                ResponseApiDto.Fail("还未收藏该商品");
            }
            int affectedRows = await _serverRepository.collectionsEFCore.DeleteAsync(collection);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> Collection(CollectionDto dto,int bid)
        {
            if(await _serverRepository.collectionsEFCore.Query(d => d.CBusinessId == bid && d.CGoodId == dto.gid).AnyAsync())
            {
                return ResponseApiDto.Fail("已收藏了该商品");
            }
            Collection collection = new Collection { CGoodId = dto.gid, CBusinessId = bid };
            int affectedRows = await _serverRepository.collectionsEFCore.AddAsync(collection);
            return ResponseApiDto.Create(affectedRows,data:collection.CId);
        }

        public async Task<ResponseApiDto> Pagination(int page,int limit,int bid)
        {
            int total = 0;
            var iq = _serverRepository.collectionsEFCore.Pagination(d=>d.CBusinessId==bid,false,d=>d.CCreateTime,out total,page,limit);
            List <ResponseCollectionsDto> data=await iq.Select(d=>new ResponseCollectionsDto { id = d.CId, good = new ResponseGoodList { name = d.CGood.GName, id = d.CGood.GId, photo = d.CGood.GPhoto, price = d.CGood.GPrice, promotePrice = d.CGood.Promotions.Where(d => d.PEndTime > DateTime.Now).FirstOrDefault()!= null ? d.CGood.Promotions.Where(d => d.PEndTime > DateTime.Now).FirstOrDefault().PDiscountPrice : 0, saleCout = d.CGood.OrderDetails.Where(d => d.OdOrder.OCompleteTime != null).Sum(d => d.OdCount), spec = d.CGood.GSpecs } }).ToListAsync();
            return ResponseApiDto.Ok("数据已获取",new {total,data});
        }
    }
}
